package cn.edu.zzu.demo03ThreadSecurity;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 显示锁
 */
public class TestLock {

    public static void main(String[] args) {
        SaleTicket saleTicket = new SaleTicket();
        new Thread(saleTicket).start();
        new Thread(saleTicket).start();
        new Thread(saleTicket).start();
    }
}

class SaleTicket implements Runnable {

    private Integer num = 10;

    private final ReentrantLock lock = new ReentrantLock(); //可重入锁

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (num > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(num--);
                } else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
